package com.sinodata.bsm.cicp.finder.ibmmq;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.CommandReader;

public class MqQueueFinder extends Finder {

    private static Logger logger = Logger.getLogger(MqQueueFinder.class.getName());

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        String mqName = (String) params.get("MQNAME");
        BufferedReader reader = null;
        List<String[]> retList = new ArrayList<String[]>();
        String ptnStr = "\\s*QUEUE\\((\\S+)\\)\\s+\\S*";
        Pattern pattern = Pattern.compile(ptnStr);
        String cmdStr = "echo \"dis ql(*)\"  | runmqsc " + mqName;
        try {
            reader = CommandReader.getReader(ip, cmdStr, 0, 0);
            String strLine = null;
            Matcher matcher = null;
            while ((strLine = reader.readLine()) != null) {
                matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    String queueName = matcher.group(1);
                    String[] info = new String[5];
                    retList.add(info);
                    info[0] = mqName + "_" + queueName;
                    info[1] = queueName;
                    info[2] = queueName + " for " + mqName;
                    info[3] = mqName; //MQ_NAME
                    info[4] = queueName; //CHANNEL_NAME
                }
            }
            return retList;
        } catch (IOException e) {
            logger.error("failed to find MqChannel", e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        return null;
    }
}
